<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          size="small">
          <el-option
            v-for="dict in dict.type.cms_blog_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['blog:blog:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['blog:blog:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['blog:blog:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['blog:blog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="blogList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cms_blog_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['blog:blog:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['blog:blog:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-folder-opened"
            @click="fileList(scope.row)"
            v-hasPermi="['blog:blog:edit']"
          >资源列表</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改博客信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容">
          <blog-editor
            v-model="form.content"
            @getOssId="getOssId"
            :min-height="192" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="releaseForm">发 布</el-button>
        <el-button :loading="buttonLoading" type="info" @click="saveForm">暂 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 资源列表对话框 -->
    <el-dialog :title="fileTitle" :visible.sync="fileListOpen" width="1000px" append-to-body>
      <el-table class="file-list" :data="fileInfoList">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="文件主键id" align="center" prop="ossId" /> -->
        <el-table-column label="图片预览" align="center" prop="url">
          <template slot-scope="scope">
            <el-image style="width: 120px;height: 60px;" :src="scope.row.url" lazy :preview-src-list="[scope.row.url]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="文件名称" align="center" prop="originalName" />
        <el-table-column label="文件类型" align="center" prop="fileSuffix" />
        <!-- <el-table-column label="存储文件名称" align="center" prop="fileObjectName" /> -->
        <!-- <el-table-column label="存储路径" align="center" prop="filePath" /> -->
        <el-table-column label="创建者" align="center" prop="createBy" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-download" @click="handleDownload(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listBlog, getBlog, delBlog, addBlog, updateBlog, getAllTagAndAllType } from "@/api/blog/blog";
import { addBatch, getFileList } from "@/api/blog/blogFile";
import { Loading } from 'element-ui';

export default {
  name: "Essay",
  dicts: ['cms_blog_status'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 默认排序
      defaultSort: {prop: 'Top,createTime', order: 'descending,descending'},
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 博客信息表格数据
      blogList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        type: 2,
        status: undefined
      },
      top: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ]
      },
      fileIds: [],
      // 按钮loading
      imageButtonLoading: false,
      // 弹出层标题
      imageTitle: "",
      // 是否显示弹出层
      imageOpen: false,
      // 表单参数
      imageForm: {},
      // 表单校验
      imageRules: {
        file: [
          { required: true, message: "文件不能为空", trigger: "blur" }
        ]
      },
      // 弹出层标题
      fileTitle: "",
      // 是否显示弹出层
      fileListOpen: false,
      // 资源列表表格数据
      fileInfoList: [],
    };
  },
  created() {
    this.queryParams.orderByColumn = this.defaultSort.prop;
    this.queryParams.isAsc = this.defaultSort.order;
    this.getList();
  },
  methods: {
    /** 查询博客信息列表 */
    getList() {
      this.loading = true;
      listBlog(this.queryParams).then(response => {
        this.blogList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        type: 2,
        content: undefined,
        top: "0",
        blogPicOssId: undefined,
        blogPicUrl: undefined,
        blogPicName: undefined,
        blogDesc: undefined,
        tagIds: [],
        typeIds: [],
      };
      this.resetForm("form");
      this.fileIds = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加博客信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getBlog(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改博客信息";
      });
    },
    /** 发布按钮 */
    releaseForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.type = 2;
          this.form.status = 1;
          if (this.top) {
            this.form.top = 1;
          } else {
            this.form.top = 0;
          }
          if (this.form.id != null) {
            updateBlog(this.form).then(response => {
              if (this.fileIds.length > 0) {
                let fileBlogInfo = {
                  blogId: this.form.id,
                  fileIds: this.fileIds
                };
                addBatch(fileBlogInfo).then(response => {});
              }
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addBlog(this.form).then(response => {
              if (this.fileIds.length > 0) {
                let fileBlogInfo = {
                  blogId: response.data,
                  fileIds: this.fileIds
                };
                addBatch(fileBlogInfo).then(response => {});
              }
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 暂存按钮 */
    saveForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.type = 2;
          this.form.status = 0;
          if (this.top) {
            this.form.top = 1;
          } else {
            this.form.top = 0;
          }
          if (this.form.id != null) {
            updateBlog(this.form).then(response => {
              if (this.fileIds.length > 0) {
                let fileBlogInfo = {
                  blogId: this.form.id,
                  fileIds: this.fileIds
                };
                addBatch(fileBlogInfo).then(response => {});
              }
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addBlog(this.form).then(response => {
              if (this.fileIds.length > 0) {
                let fileBlogInfo = {
                  blogId: response.data,
                  fileIds: this.fileIds
                };
                addBatch(fileBlogInfo).then(response => {});
              }
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除博客信息编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delBlog(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('blog/blog/export', {
        ...this.queryParams
      }, `blog_${new Date().getTime()}.xlsx`)
    },
    getOssId(data) {
      this.fileIds.push(data);
    },
    /** 资源列表按钮操作 */
    fileList(row) {
      let loadingInstance = Loading.service({
        target: ".file-list"
      });
      this.reset();
      const blogId = row.id || this.ids
      getFileList(blogId).then(response => {
        this.fileInfoList = response.data;
        this.fileListOpen = true;
        this.fileTitle = "资源列表";
        setTimeout(() => {
          loadingInstance.close();
        }, 100);
      });
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      this.$download.oss(row.ossId)
    },
  }
};
</script>
